#!/bin/bash

ALIEN_PACKAGES_AFS_DIR=${ALIEN_PACKAGES_AFS_DIR:-"::PACKAGES_BASE_DIR::"}
ALIEN_PACKAGES_AFS_SCRIPTS_DIR=${ALIEN_PACKAGES_AFS_SCRIPTS_DIR:-"::PACKAGES_BASE_DIR::"}
ALIEN_DIR=${ALIEN_DIR:-"::ALIEN_BASE_DIR::"}
ALICE_USERNAME=${ALICE_USERNAME:-`id -u -n`}
ALICE_ROOT_VERSION_TYPE=${ALICE_ROOT_VERSION_TYPE:-"AN"}
ALICE_CHECK_ALIEN_TOKEN=${ALICE_CHECK_ALIEN_TOKEN:-"NO"}
ALICE_CERTIFICATE_PATH=${ALICE_CERTIFICATE_PATH:-"$HOME/.globus"}

export ALIEN_PACKAGES_AFS_DIR ALIEN_DIR ALICE_USERNAME ALICE_ROOT_VERSION_TYPE

function DoAll() {

if [ ! -z $1 ];then
  MY_ALICROOT_TAG="$1"
  MY_ALICROOT_TAG=`echo $MY_ALICROOT_TAG | sed 's/@/\//' | sed 's/::/\//'`
  if [ ! -d $ALIEN_PACKAGES_AFS_DIR/$MY_ALICROOT_TAG ]; then
    echo "+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"
    echo ""
    echo "Error : AliRoot $1 is NOT available !"
    echo "        Directory $ALIEN_PACKAGES_AFS_DIR/$MY_ALICROOT_TAG doesn't exist !"
    echo ""
    echo "Tip : Maybe correct version is VO_ALICE@AliRoot::$1"
    echo ""
    echo "+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"
    return 1
  fi
fi

if [ ! -z $2 ];then
  MY_ALICROOT_TAG="$2"
  MY_ALICROOT_TAG=`echo $MY_ALICROOT_TAG | sed 's/@/\//' | sed 's/::/\//'`
  if [ ! -d $ALIEN_PACKAGES_AFS_DIR/$MY_ALICROOT_TAG ]; then
    echo "+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"
    echo ""
    echo "Error : ROOT $2 is NOT available !"
    echo "        Directory $ALIEN_PACKAGES_AFS_DIR/$MY_ALICROOT_TAG doesn't exist !"
    echo ""
    echo "Tip : Maybe correct version is VO_ALICE@ROOT::$2"
    echo ""
    echo "+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"
    return 1
  fi
fi

PACKAGES_DEP_FILE="$ALIEN_PACKAGES_AFS_DIR/download/Packages"
                  
#ROOT_LATEST=`find $ALIEN_PACKAGES_AFS_DIR/VO_ALICE/ROOT/ -maxdepth 1 -mindepth 1 -type d | awk -F/ '{print $NF}' | sort | tail -n1`
if [ "$ALICE_ROOT_VERSION_TYPE" == "REV" ]; then
  ALIROOT_AN_LATEST=`find $ALIEN_PACKAGES_AFS_DIR/VO_ALICE/AliRoot/ -maxdepth 1 -mindepth 1 -type d | grep "Rev" | awk -F/ '{print $NF}' | sort | tail -n1`
else
  ALIROOT_AN_LATEST=`find $ALIEN_PACKAGES_AFS_DIR/VO_ALICE/AliRoot/ -maxdepth 1 -mindepth 1 -type d | grep "AN" | awk -F/ '{print $NF}' | sort | tail -n1`
fi

if [ -z "$1" ] || [ "x$1" == "xPRO"  ];then
  ALICROOT_TAG="VO_ALICE@AliRoot::$ALIROOT_AN_LATEST"
else
  ALICROOT_TAG="$1"
  ALIROOT_AN_LATEST="$1"
  ALIROOT_AN_LATEST=${ALIROOT_AN_LATEST/@/\/}
  ALIROOT_AN_LATEST=${ALIROOT_AN_LATEST/::/\/}
  ALIROOT_AN_LATEST=`basename $ALIROOT_AN_LATEST`
fi

ALICROOT_TAG=${ALICROOT_TAG/@/\/}
ALICROOT_TAG=${ALICROOT_TAG/::/\/}


if [ -z $ALIROOT_AN_LATEST ]; then
  echo "There is no available version for \"$ALICE_ROOT_VERSION_TYPE\" !!!!"
  return 10
fi

if [ ! -d $ALIEN_PACKAGES_AFS_DIR/$ALICROOT_TAG/`basename $ALICROOT_TAG` ]; then
  echo "AliRoot version \"`basename $ALICROOT_TAG`\" is not available !!!!"
  return 11
fi

# echo "$ALIROOT_AN_LATEST"

if [ ! -f $PACKAGES_DEP_FILE ]; then
  PACKAGES_DEP_FILE="/tmp/Packages_$USER"
  rm -Rf $PACKAGES_DEP_FILE &>/dev/null
  if ! wget -q "http://pcalienbuild4.cern.ch:8889/tarballs/Packages" -O $PACKAGES_DEP_FILE ; then
    echo "Could not download the Packages file from the build servers, can't work without it, sorry"
    exit 1
  fi
fi

NO_DEFAULT_ROOT=""
if [ -z "$2" ] || [ "x$1" == "xPRO" ];then
  ROOT_LATEST=`cat $PACKAGES_DEP_FILE | grep "VO_ALICE@AliRoot::${ALIROOT_AN_LATEST}[[:space:]]" | awk '{print $6}' | awk -F, '{print $1}'`
  ROOT_TAG="$ROOT_LATEST"
  ROOT_TAG=${ROOT_TAG/@/\/} 
  ROOT_TAG=${ROOT_TAG/::/\/}
  if [ ! -d $ALIEN_PACKAGES_AFS_DIR/$ROOT_TAG/`basename $ROOT_TAG` ]; then
    NO_DEFAULT_ROOT="* "
    ROOT_LATEST=`find $ALIEN_PACKAGES_AFS_DIR/VO_ALICE/ROOT/ -maxdepth 1 -mindepth 1 -type d | awk -F/ '{print $NF}' | sort | tail -n1`
    ROOT_TAG="VO_ALICE@ROOT::$ROOT_LATEST"
  fi
else
  ROOT_TAG="$2"
fi

if [ -z "$3" ] || [ "x$1" == "xPRO" ];then
  GEANT3_LATEST=`cat $PACKAGES_DEP_FILE | grep "${ALIROOT_AN_LATEST}[[:space:]]" | awk '{print $6}' | awk -F, '{print $2}'`
  GEANT3_TAG="$GEANT3_LATEST"
  GEANT3_TAG=${GEANT3_TAG/@/\/} 
  GEANT3_TAG=${GEANT3_TAG/::/\/}
  if [ ! -d $ALIEN_PACKAGES_AFS_DIR/$GEANT3_TAG/`basename $GEANT3_TAG` ]; then
    GEANT3_LATEST=`find $ALIEN_PACKAGES_AFS_DIR/VO_ALICE/GEANT3/ -maxdepth 1 -mindepth 1 -type d | awk -F/ '{print $NF}' | sort | tail -n1`
    GEANT3_TAG="VO_ALICE@GEANT3::$GEANT3_LATEST"
  fi
else
  GEANT3_TAG="$2"
fi

if [ ! -h "$ALIEN_PACKAGES_AFS_DIR/lib/libgfortran.so.1" ]; then
  if [ ! -h "/usr/lib/libgfortran.so.1" ]; then
    for DIRNAME in / /usr /usr/local; do
	    for FILENAME in $DIRNAME/lib/libgfortran.so.3 $DIRNAME/lib64/libgfortran.so.3 $DIRNAME/lib32/libgfortran.so.3; do
	      if [ -f "$FILENAME" ]; then
		     echo "Found libgfortran as $FILENAME"
         mkdir -p "$ALIEN_PACKAGES_AFS_DIR/lib" &>/dev/null
    		 ln -sf $FILENAME "$ALIEN_PACKAGES_AFS_DIR/lib/libgfortran.so.1" &>/dev/null
    		 break
	    fi
	    done
    done
  fi
fi

if [ ! -h "$ALIEN_PACKAGES_AFS_DIR/lib/libtiff.so.3" ]; then
  if [ ! -h "/usr/lib/libtiff.so.3" ]; then
    for DIRNAME in / /usr /usr/local; do
      for FILENAME in $DIRNAME/lib/libtiff.so.4 $DIRNAME/lib64/libtiff.so.4 $DIRNAME/lib32/libtiff.so.4; do
        if [ -f "$FILENAME" ]; then
          echo "Found libtiff as $FILENAME"
          mkdir -p "$ALIEN_PACKAGES_AFS_DIR/lib" &>/dev/null
          ln -sf $FILENAME "$ALIEN_PACKAGES_AFS_DIR/lib/libtiff.so.3" &>/dev/null
          break
        fi
      done
    done
  fi
fi

ROOT_TAG=${ROOT_TAG/@/\/} 
ROOT_TAG=${ROOT_TAG/::/\/}

GEANT3_TAG=${GEANT3_TAG/@/\/} 
GEANT3_TAG=${GEANT3_TAG/::/\/}

if [ -z "$LD_LIBRARY_DEFAULT" ]; then
    export LD_LIBRARY_DEFAULT="$LD_LIBRARY_PATH"
fi

if [ -z "$PATH_DEFAULT" ]; then
    export PATH_DEFAULT="$PATH"
fi

export LD_LIBRARY_PATH="$ALIEN_DIR/api/lib:$ALIEN_DIR/lib:$LD_LIBRARY_DEFAULT:$ALIEN_PACKAGES_AFS_DIR/lib"
export PATH="$ALIEN_DIR/api/bin:$ALIEN_DIR/bin:$PATH_DEFAULT"

export ROOTSYS="$ALIEN_PACKAGES_AFS_DIR/$ROOT_TAG/`basename $ROOT_TAG`"
export LD_LIBRARY_PATH="$ROOTSYS/lib:$LD_LIBRARY_PATH"
export PATH="$ROOTSYS/bin:$PATH"
export X509_CERT_DIR="$ALIEN_DIR/globus/share/certificates"
# export X509_CERT_DIR="$ROOTSYS/share/certificates"
export XrdSecSSLCADIR="$X509_CERT_DIR"

export ALICE_ROOT="$ALIEN_PACKAGES_AFS_DIR/$ALICROOT_TAG/`basename $ALICROOT_TAG`"

export GSHELL_NO_GCC=1
export GSHELL_ROOT="$ALIEN_DIR/api"
# export GSHELL_ROOT="$ROOTSYS"

export ALICE_TARGET=`root-config --arch`
export GEANT3="$ALIEN_PACKAGES_AFS_DIR/$GEANT3_TAG/`basename $GEANT3_TAG`"
export LD_LIBRARY_PATH=$GEANT3/lib/tgt_${ALICE_TARGET}:$LD_LIBRARY_PATH

export LD_LIBRARY_PATH=$ALICE_ROOT/lib/tgt_${ALICE_TARGET}:$LD_LIBRARY_PATH
export PATH=$ALICE_ROOT/bin/tgt_${ALICE_TARGET}:$PATH
export ALICE="$ALIEN_PACKAGES_AFS_DIR/$ALICROOT_TAG/"
echo "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"
echo ""
echo "Currently running : AliEn   `basename $ALIEN_DIR` $ALIEN_DIR"
echo "                  : ROOT    ${NO_DEFAULT_ROOT}VO_ALICE@ROOT::`basename $ALIEN_PACKAGES_AFS_DIR/$ROOT_TAG` $ROOTSYS"
echo "                  : GEANT3  VO_ALICE@geant3::`basename $ALIEN_PACKAGES_AFS_DIR/$GEANT3_TAG` $GEANT3"
echo "                  : AliROOT VO_ALICE@AliRoot::`basename $ALIEN_PACKAGES_AFS_DIR/$ALICROOT_TAG` $ALICE_ROOT"
echo ""
echo "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"
}

CheckCertificate() {
  
  echo "Checking AliEn token ..."  
  if [ ! -e /tmp/x509up_u$UID ];then
    alien-token-destroy &>/dev/null
    echo "================================================"
    echo "Doing \"xrdgsiproxy init\" for you ..."
    echo "================================================"
    xrdgsiproxy init -cert $ALICE_CERTIFICATE_PATH/usercert.pem -key $ALICE_CERTIFICATE_PATH/userkey.pem
  fi
  
  if [ ! -e /tmp/x509up_u$UID ];then
    echo "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"
    echo "Wrong password or problem with certificate !!!! Exiting ..."
    echo "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"
    return 2
  fi
  
  if ! alien-token-info &>/dev/null  ;then
    if [ -z $ALICE_USERNAME ]; then
      ALICE_USERNAME=$USER
    fi
    echo "================================================"
    echo "Doing \"alien-token-init $ALICE_USERNAME\" for you ..."
    echo "================================================"
    alien-token-init $ALICE_USERNAME
  fi
  
  if ! alien-token-info &>/dev/null  ;then
    echo "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"
    echo "AliEn token was not created !!!! Exiting ..."
    echo "If the AliEn username is not '${ALICE_USERNAME}', then please set the ALICE_USERANME environment variable"
    echo "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"
    return 3
  fi
  
}

function ShowAliRootVersions() {
  echo ""
  echo "Welcome to ALICE"
  echo ""
  echo "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"
  echo ""
  echo "Available AliRoot versions: "
  for MY_ALIROOT_VER in `ls $ALIEN_PACKAGES_AFS_DIR/VO_ALICE/AliRoot/ | sort `; do
    echo "                             VO_ALICE@AliRoot::$MY_ALIROOT_VER"
  done
  echo ""
  echo "To change AliRoot version do :"
  echo "             source $ALIEN_PACKAGES_AFS_SCRIPTS_DIR/env_aliroot.bash <VO_ALICE@AliRoot::aliroot verion>"
  echo ""
  echo "Following example showing u how to setup latest Rev of AliRoot :"
  MY_RET=`find $ALIEN_PACKAGES_AFS_DIR/VO_ALICE/AliRoot/ -maxdepth 1 -mindepth 1 -type d | grep "Rev" | awk -F/ '{print $NF}' | sort | tail -n1`
  echo "             source $ALIEN_PACKAGES_AFS_SCRIPTS_DIR/env_aliroot.bash VO_ALICE@AliRoot::$MY_RET"
  echo ""
  if [ "$ALICE_ROOT_VERSION_TYPE" == "REV" ]; then
    ALIROOT_AN_LATEST=`find $ALIEN_PACKAGES_AFS_DIR/VO_ALICE/AliRoot/ -maxdepth 1 -mindepth 1 -type d | grep "Rev" | awk -F/ '{print $NF}' | sort | tail -n1`
  else
    ALIROOT_AN_LATEST=`find $ALIEN_PACKAGES_AFS_DIR/VO_ALICE/AliRoot/ -maxdepth 1 -mindepth 1 -type d | grep "AN" | awk -F/ '{print $NF}' | sort | tail -n1`
  fi
  echo "By default latest AliRoot AN version is set : VO_ALICE@AliRoot::`basename $ALIEN_PACKAGES_AFS_DIR/$ALIROOT_AN_LATEST`"
  echo ""
}

ShowAliRootVersions

DoAll $1 $2
if [ "$?" == "0" ]; then
  echo "ALIROOT variables OK"
else
  echo "Env. variables Failed !!!"
  return 10
fi

if [ "$ALICE_CHECK_ALIEN_TOKEN" == "YES" ];then
  CheckCertificate
  RET="$?"
  if [ "$RET" == "0" ]; then
    echo "AliEn token is OK"
  else
    echo "AliEn token is failed !!!"
  fi
  return $RET
fi

PACKAGES_DEP_FILE="/tmp/Packages_$USER"
rm -Rf $PACKAGES_DEP_FILE &>/dev/null

if [ "$?" == "0" ]; then
  echo "All OK"
else
  echo "Failed !!!"
fi

